import requests
from requests.exceptions import RequestException, Timeout


class HttpRequest:
    def __init__(self, base_url=None, headers=None):
        # 设置默认的 base_url 和 headers
        self.base_url = base_url
        self.headers = headers if headers else {'User-Agent': 'Python/HttpRequest'}

    def get(self, url, params=None, headers=None, timeout=3000):
        """发送 GET 请求"""
        try:
            response = requests.get(self._build_url(url), params=params, headers=headers or self.headers,
                                    timeout=timeout,verify=False)
            response.raise_for_status()  # 如果状态码不是2xx，会抛出异常
            return response.json() if response.headers.get('Content-Type') == 'application/json' else response.text
        except RequestException as e:
            print(f"GET 请求错误: {e}")
        except Timeout:
            print("请求超时")

    def post(self, url, data=None, json=None, headers=None, timeout=3000):
        """发送 POST 请求"""
        try:
            response = requests.post(self._build_url(url), data=data, json=json, headers=headers or self.headers,
                                     timeout=timeout,verify=False)
            response.raise_for_status()  # 如果状态码不是2xx，会抛出异常
            return response.json() if response.headers.get('Content-Type') == 'application/json' else response.text
        except RequestException as e:
            print(f"POST 请求错误: {e}")
        except Timeout:
            print("请求超时")

    def put(self, url, data=None, headers=None, timeout=10):
        """发送 PUT 请求"""
        try:
            response = requests.put(self._build_url(url), data=data, headers=headers or self.headers, timeout=timeout)
            response.raise_for_status()
            return response.json() if response.headers.get('Content-Type') == 'application/json' else response.text
        except RequestException as e:
            print(f"PUT 请求错误: {e}")
        except Timeout:
            print("请求超时")

    def delete(self, url, headers=None, timeout=10):
        """发送 DELETE 请求"""
        try:
            response = requests.delete(self._build_url(url), headers=headers or self.headers, timeout=timeout)
            response.raise_for_status()
            return response.json() if response.headers.get('Content-Type') == 'application/json' else response.text
        except RequestException as e:
            print(f"DELETE 请求错误: {e}")
        except Timeout:
            print("请求超时")

    def _build_url(self, url):
        """构建完整的请求 URL"""
        if self.base_url:
            return f"{self.base_url}/{url}"
        return url


# # 示例使用：
# if __name__ == '__main__':
#     # 实例化工具类
#     http_client = HttpRequest(base_url="https://jsonplaceholder.typicode.com")
#
#     # 发送 GET 请求
#     response = http_client.get("posts")
#     print(response)
#
#     # 发送 POST 请求
#     data = {"title": "foo", "body": "bar", "userId": 1}
#     response = http_client.post("posts", json=data)
#     print(response)
#
#     # 发送 PUT 请求
#     data = {"id": 1, "title": "updated title", "body": "updated body", "userId": 1}
#     response = http_client.put("posts/1", json=data)
#     print(response)
#
#     # 发送 DELETE 请求
#     response = http_client.delete("posts/1")
#     print(response)
